import axios from 'axios/index';
import JsonP from 'jsonp'; //todo kim-stamp jsonp跨域
import jsonp from 'fetch-jsonp'; //todo kim-stamp fetch-jsonp跨域
import querystring from 'querystring'; //JavaScript与json格式转换
import { Modal, message, notification } from 'antd/lib/index';
import qs from 'qs';
import router from 'umi/router';
import React from 'react';

const ERR_RETURN_DURATION = 3; //错误提示间隔时间

export default class Axios {
  static explain = '这只是静态方法或者是静态变量';

  static jsonp({ url }) {
    return new Promise((resolve, reject) => {
      JsonP(url, { param: 'callback' }, function(err, res) {
        if (res.status !== 'success') return reject(res.messsage);
        return resolve(res);
      });
    });
  }

  static fetch(keywords, callback) {
    let timeout, currentKeywords;
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    currentKeywords = keywords;

    function fake() {
      const str = querystring.encode({
        code: 'utf-8',
        q: keywords,
      });
      jsonp(`https://suggest.taobao.com/sug?${str}`)
        .then(response => response.json()) //会给回一个 Promise对象
        .then(res => {
          if (currentKeywords === keywords) {
            const { result } = res;
            const data = [];
            result.forEach(item => {
              data.push({
                keywords: item[0],
                text: item[0],
              });
            });
            callback(data);
          }
        });
    }

    timeout = setTimeout(fake, 100);
  }

  static ajax(options, method = 'get') {
    // let loading;
    // if (options.data && options.data.isShowLoading !== false) {
    // }
    // console.log(options, '请求的参数');
    return new Promise((resolve, reject) => {
      axios({
        // baseURL: "https://www.easy-mock.com/mock/5d2dcb9a934181050dd4ae65/api",
        url: options.url,
        method: method,
        timeout: 5000,
        params: { ...options.params, _channelType: 'ajax' } || '',
        // params: qs.stringify(options.data) || "",
        headers: { ACJSESSIONID: sessionStorage.getItem('ACJSESSIONID') },
        // headers: { [Constants.ACJSESSIONID]: sessionStorage.getItem(Constants.ACJSESSIONID) },
      })
        .then(response => {
          // if (options.data && options.data.isShowLoading !== false) {
          //   loading = document.getElementById("ajaxLoading");
          //   loading.style.display = "none";
          // }
          if (response.status == '200') {
            let res = response.data;
            resolve(res);
            if (res.resultCode !== 'ok') {
              if (errCount === 0) {
                errCount++;
                notification.error({
                  message: `错误码 ${response.resultCode}`,
                  description: (
                    <div>
                      {response.errMessage}。
                      {response.resultCode === 'SESSION_ERROR' ? (
                        <a
                          onClick={() => {
                            router.push('/user/login?redirect=' + window.location.href);
                          }}
                        >
                          跳转至登录页
                        </a>
                      ) : (
                        ''
                      )}
                    </div>
                  ),
                  onClose: () => {
                    errCount--;
                  },
                });
              }
            }

            // if (res.resultCode == "ok") {
            // } else {
            //   Modal.info({
            //     title: "提示",
            //     content: res.errMessage
            //   });
            // }
          } else {
            reject(response.data);
          }
        })
        .catch(err => {
          // loading = document.getElementById("ajaxLoading");
          // loading.style.display = "none";
          Modal.info({
            title: '提示',
            content: '网络请求错误',
          });
        });
    });
  }

  static get(url, param) {
    console.log(url);
    return new Promise((resolve, reject) => {
      axios.get(url, param).then(res => {
        if (res.status === 200) {
          resolve(res);
        }
        if (res && res.status !== 200) {
          reject(res);
          return message.error('请求的状态码不是200', ERR_RETURN_DURATION);
        }
      });
    }).catch(err => {
      return message.warning(err);
    });
  }

  static post(url, param) {
    console.log(url);
    return new Promise((resolve, reject) => {
      axios.post(url, param).then(res => {
        if (res.status === 200) {
          message.info(res.data.errMessage);
          return resolve(res);
        }
        reject(res.data);
        return message.error('请求的状态码不是200');
      });
    });
  }
}
